package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.Order;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.service.OrderService;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 订单管理控制器
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    public Result<String> createOrder(@RequestBody Order order) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer buyerId = Integer.parseInt(claims.get("id").toString());
        order.setBuyerId(buyerId);
        
        String message = orderService.createOrder(order);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 更新订单状态
     */
    @PutMapping("/status/{orderId}")
    public Result<String> updateOrderStatus(@PathVariable Integer orderId, @RequestParam String status) {
        String message = orderService.updateOrderStatus(orderId, status);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 更新订单信息
     */
    @PutMapping("/update")
    public Result<String> updateOrder(@RequestBody Order order) {
        String message = orderService.updateOrder(order);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 根据订单ID查询订单详情
     */
    @GetMapping("/detail/{orderId}")
    public Result<Order> getOrderDetail(@PathVariable Integer orderId) {
        Order order = orderService.getOrderById(orderId);
        if (order == null) {
            return Result.error("订单不存在");
        }
        return Result.success(order);
    }
    
    /**
     * 根据订单号查询订单
     */
    @GetMapping("/code/{code}")
    public Result<Order> getOrderByCode(@PathVariable String code) {
        Order order = orderService.getOrderByCode(code);
        if (order == null) {
            return Result.error("订单不存在");
        }
        return Result.success(order);
    }
    
    /**
     * 查询我的购买订单
     */
    @GetMapping("/myOrders")
    public Result<List<Order>> getMyOrders() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer buyerId = Integer.parseInt(claims.get("id").toString());
        
        List<Order> orders = orderService.getOrdersByBuyerId(buyerId);
        return Result.success(orders);
    }
    
    /**
     * 查询我的销售订单
     */
    @GetMapping("/mySales")
    public Result<List<Order>> getMySales() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer sellerId = Integer.parseInt(claims.get("id").toString());
        
        List<Order> orders = orderService.getOrdersBySellerId(sellerId);
        return Result.success(orders);
    }
    
    /**
     * 根据状态查询订单
     */
    @GetMapping("/status/{status}")
    public Result<List<Order>> getOrdersByStatus(@PathVariable String status) {
        List<Order> orders = orderService.getOrdersByStatus(status);
        return Result.success(orders);
    }
    
    /**
     * 取消订单
     */
    @PutMapping("/cancel/{orderId}")
    public Result<String> cancelOrder(@PathVariable Integer orderId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        String message = orderService.cancelOrder(orderId, userId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 删除订单（仅管理员）
     */
    @DeleteMapping("/delete/{orderId}")
    public Result<String> deleteOrder(@PathVariable Integer orderId) {
        String message = orderService.deleteOrder(orderId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 确认收货
     */
    @PutMapping("/confirm/{orderId}")
    public Result<String> confirmOrder(@PathVariable Integer orderId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        // 验证订单是否存在且用户是买家
        Order order = orderService.getOrderById(orderId);
        if (order == null) {
            return Result.error("订单不存在");
        }
        if (!order.getBuyerId().equals(userId)) {
            return Result.error("无权限确认此订单");
        }
        
        String message = orderService.updateOrderStatus(orderId, "delivered");
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 发货
     */
    @PutMapping("/ship/{orderId}")
    public Result<String> shipOrder(@PathVariable Integer orderId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        // 验证订单是否存在且用户是卖家
        Order order = orderService.getOrderById(orderId);
        if (order == null) {
            return Result.error("订单不存在");
        }
        if (!order.getSellerId().equals(userId)) {
            return Result.error("无权限操作此订单");
        }
        
        String message = orderService.updateOrderStatus(orderId, "shipped");
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 模拟支付功能
     * 将订单状态改为已支付，商品状态改为已售出
     */
    @PutMapping("/pay/{orderId}")
    public Result<String> payOrder(@PathVariable Integer orderId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        String message = orderService.payOrder(orderId, userId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 卖家发货（新版本，带权限验证）
     */
    @PutMapping("/ship-new/{orderId}")
    public Result<String> shipOrderNew(@PathVariable Integer orderId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        String message = orderService.shipOrder(orderId, userId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
    
    /**
     * 买家确认收货（新版本，带权限验证）
     */
    @PutMapping("/confirm-new/{orderId}")
    public Result<String> confirmReceiptNew(@PathVariable Integer orderId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        String message = orderService.confirmReceipt(orderId, userId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
}